Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
Why can't I get "res" object console logged inside the callback of app.listen in node.js
const http = require('http') 
const server = http.createServer(()=>{
            console.log("created server")
        });
const port = 3000;
server.listen(port, (req,res) => {console.log(res)})

// in console => undefined

//after opening the page => in console => created server

// no res obj in console

why can't "res" be consolelogged even after "created server" is console logged and "http://localhost:3000" is opened too?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

why can't "res" be consolelogged even after "created server" is console logged

The callback to server.listen() just tells you when your server has been started. It is not passed req or res as there is no active incoming http connection at the moment your server has just started.

req and res get passed to listeners for the request event which you can register for either by passing a callback to http.createServer() as in:

const server = http.createServer((req, res) => {
    console.log(res);
    res.end("hello");
});

Or, by registering a listener for the request event as in:

server.on('request', (req, res) => {
    console.log(res);
    res.end("hello");
});

So, it appears in your code that you just have the callbacks to http.createServer() and server.listen() reversed. It's the one to http.createServer() that is called with req and res, not the callback to server.listen(). That callback to server.listen() tells you when the server has been successfully started. The callback to http.createServer() tells you when an incoming http request has arrived and it passes req and res to that callback.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda